<script setup>
import { onMounted, onUpdated, ref } from "vue";
import http from "@/utils/http.js";
import { userStore } from "@/stores/userStore.js";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

const router = useRouter();
const uStore = userStore();

const total = ref(0);
const addressData = ref([]);
const params = ref({
    page: 1,
    pageSize: 50,
    userId: uStore.userInfo.data.userId,
});

const getAddress = async () => {
    try {
        const res = await http.get("/addresses/personal", { params: params.value });
        total.value = res.data.total;
        addressData.value = res.data.rows;
    } catch (error) {
        console.error("获取地址列表失败:", error);
        addressData.value = [];
    }
};

const dialogAddress = ref(false);

const activeAddress = ref({});
const switchAddress = (item) => {
    activeAddress.value = item;
};

const itemData = ref([])
const getItem = async () => {
    const res = await http.get('/items/' + uStore.userInfo.data.userId)
    itemData.value = res.data
    console.log('itemData:', itemData.value)
}

const count = ref({
    sum: 0,
    price: 0,
});

const goodsIds = ref([]);

const sumPrice = () => {
    const num = ref(0);
    const allPrice = ref(0);
    const ids = ref([]);

    itemData.value.forEach((g) => {
        if (g && g.state === 1) {
            num.value++;
            allPrice.value += g.goodsPrice;

            ids.value.push(g.goodsId);
        }
    });

    count.value.sum = num.value;
    count.value.price = allPrice.value;
    goodsIds.value = ids.value;
};

const addOrder = ref({
    orderUser: uStore.userInfo.data.userId,
    orderGoods: "",
    orderAddress: "",
    orderPrice: "",
});

const submitOrder = async () => {
    if (!activeAddress.value || !activeAddress.value.addressId) {
        ElMessage.error("请选择收货地址");
        return;
    }

    addOrder.value.orderGoods = goodsIds.value.toString();
    addOrder.value.orderAddress = activeAddress.value.addressId;
    addOrder.value.orderPrice = count.value.price.toString();

    const res = await http.post("/orders/add", addOrder.value);

    if (res.code === 666) {
        await router.replace({ path: "/pay" });
    }
};

const to = () => {
    router.replace({ path: "/Cart" });
};

onMounted(() => {
    getAddress();
    getItem();
});

onUpdated(() => {
    sumPrice();
});
</script>

<template>
    <div class="custom-checkout-page">
        <!-- 返回购物车 -->
        <el-button type="primary" class="back-btn" @click="to()">返回购物车</el-button>

        <!-- 内容容器 -->
        <div class="checkout-container">
            <!-- 收货地址 -->
            <section class="checkout-section">
                <h3 class="section-title">收货地址</h3>
                <div class="address-card">
                    <div v-if="!activeAddress" class="no-address">
                        您需要先添加收货地址才可提交订单。
                    </div>
                    <div v-else class="address-info">
                        <p><strong>收货人：</strong>{{ activeAddress.consigneeName }}</p>
                        <p><strong>联系方式：</strong>{{ activeAddress.consigneePhone }}</p>
                        <p><strong>收货地址：</strong>{{ activeAddress.addressName }}</p>
                    </div>
                    <el-button @click="dialogAddress = true" round>切换地址</el-button>
                </div>
            </section>

            <!-- 商品信息 -->
            <section class="checkout-section">
                <h3 class="section-title">商品信息</h3>
                <div class="goods-card-list">
                    <template v-for="i in itemData" :key="i.goodsId">
                        <div class="goods-card" v-if="i.state === 1">
                            <img :src="i.goodsPhoto" alt="商品图片" class="goods-image" />
                            <div class="goods-details">
                                <h4>{{ i.goodsName }}</h4>
                                <p>{{ i.goodsDescription }}</p>
                                <span class="price">&yen;{{ i.goodsPrice }}</span>
                            </div>
                        </div>
                    </template>
                </div>
            </section>

            <!-- 金额明细 -->
            <section class="checkout-section">
                <h3 class="section-title">金额明细</h3>
                <div class="summary-card">
                    <div class="summary-row">
                        <span>商品件数：</span>
                        <span>{{ count.sum }} 件</span>
                    </div>
                    <div class="summary-row total">
                        <span>应付总额：</span>
                        <span class="total-price">&yen;{{ count.price }}</span>
                    </div>
                </div>
            </section>

            <!-- 提交订单 -->
            <div class="submit-order">
                <el-button type="primary" size="large" @click="submitOrder()">立即提交订单</el-button>
            </div>
        </div>

        <!-- 地址弹窗 -->
        <el-dialog title="选择收货地址" v-model="dialogAddress" width="30%">
            <div class="address-options">
                <div v-for="item in addressData" :key="item.addressId" class="address-option"
                    @click="switchAddress(item)" :class="{ active: item.addressId === activeAddress?.addressId }">
                    <p><strong>收货人：</strong>{{ item.consigneeName }}</p>
                    <p><strong>电话：</strong>{{ item.consigneePhone }}</p>
                    <p><strong>地址：</strong>{{ item.addressName }}</p>
                </div>
            </div>
            <template #footer>
                <el-button @click="dialogAddress = false">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped lang="scss">.custom-checkout-page {
    background-color: #f2f4f8;
    padding: 40px 20px;
    font-family: 'Poppins', sans-serif;
  
    .back-btn {
      margin-bottom: 20px;
      float: right;
      background: linear-gradient(135deg, #9b59b6, #e74c3c);
      color: white;
      border: none;
      transition: all 0.3s ease;
  
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }
    }
  
    .checkout-container {
      max-width: 1000px;
      margin: 0 auto;
      background: #fff;
      border-radius: 16px;
      box-shadow: 0 6px 20px rgba(0, 0, 0, 0.05);
      padding: 30px;
    }
  
    .checkout-section {
      margin-bottom: 30px;
  
      .section-title {
        font-size: 20px;
        color: #333;
        margin-bottom: 16px;
        border-left: 5px solid #9b59b6;
        padding-left: 12px;
        font-weight: 600;
      }
    }
  
    .address-card {
      background: #fdfdfd;
      border: 1px solid #e0e0e0;
      border-radius: 12px;
      padding: 20px;
      display: flex;
      flex-direction: column;
      gap: 10px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
  
      .no-address {
        color: #999;
        text-align: center;
        font-size: 15px;
      }
  
      .address-info {
        line-height: 1.8;
        color: #333;
      }
  
      button {
        align-self: flex-start;
        background: linear-gradient(135deg, #9b59b6, #e74c3c);
        color: white;
        border: none;
        transition: all 0.3s ease;
  
        &:hover {
          transform: scale(1.03);
          box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
        }
      }
    }
  
    .goods-card-list {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }
  
    .goods-card {
      display: flex;
      gap: 20px;
      background: #ffffff;
      border-radius: 12px;
      padding: 16px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
      transition: transform 0.3s ease, box-shadow 0.3s ease;
  
      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
      }
  
      .goods-image {
        width: 100px;
        height: 100px;
        object-fit: cover;
        border-radius: 8px;
        transition: transform 0.3s ease;
      }
  
      .goods-details {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
  
        h4 {
          font-size: 16px;
          margin: 0;
          color: #2d3436;
        }
  
        p {
          margin: 5px 0;
          color: #7f8c8d;
        }
  
        .price {
          font-weight: bold;
          color: #e67e22;
          font-size: 16px;
        }
      }
    }
  
    .summary-card {
      background: #fafafa;
      border-radius: 12px;
      padding: 20px;
      border: 1px solid #eee;
  
      .summary-row {
        display: flex;
        justify-content: space-between;
        padding: 10px 0;
        font-size: 16px;
        color: #333;
  
        &.total {
          font-weight: bold;
          border-top: 1px dashed #ccc;
          padding-top: 14px;
        }
  
        .total-price {
          color: #e74c3c;
          font-size: 20px;
        }
      }
    }
  
    .submit-order {
      text-align: right;
      margin-top: 30px;
    }
  
    .address-options {
      display: flex;
      flex-direction: column;
      gap: 15px;
    }
  
    .address-option {
      padding: 15px;
      border: 1px solid #ddd;
      border-radius: 10px;
      cursor: pointer;
      transition: all 0.3s ease;
  
      &:hover,
      &.active {
        border-color: #9b59b6;
        background: #f3e8ff;
      }
    }
  }
</style>